#include "database.h"
sqlite3 *db;
void database_init()
{
    const char *db_path = "../database/node.db"; // 数据库路径
    char *zErrMsg = NULL;
    int rc;

    // 打开或创建数据库
    rc = sqlite3_open(db_path, &db);
    if (rc != SQLITE_OK)
    {
        fprintf(stderr, "无法打开数据库: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db); // 释放资源
        db = NULL;
        return;
    }

    printf("数据库打开成功（或已创建）：%s\n", db_path);

    // 创建表 SQL
    const char *create_table_sql =
        "CREATE TABLE IF NOT EXISTS node ("
        "time INTEGER NOT NULL, "
        "key INTEGER NOT NULL, "
        "type INTEGER NOT NULL, "
        "val TEXT NOT NULL);";

    // 执行建表语句
    rc = sqlite3_exec(db, create_table_sql, 0, 0, &zErrMsg);
    if (rc != SQLITE_OK)
    {
        fprintf(stderr, "建表失败: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
        sqlite3_close(db);
        db = NULL;
        return;
    }

    printf("表 node 创建成功（或已存在）。\n");
}
// 插入函数
int insert_data_to_db(int key, int type, union val_t val, time_t ts)
{

    sqlite3_stmt *stmt;
    const char *sql = "INSERT INTO node (key, val, type, time) VALUES (?, ?, ?, ?);";

    // 预编译语句
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK)
    {
        fprintf(stderr, "SQL 预编译失败: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
        return -1;
    }

    // 转换 val 为字符串表示
    char val_str[64] = {0};
    switch (type)
    {
    case TYPE_BOOL:
        snprintf(val_str, sizeof(val_str), "%d", val.b_val ? 1 : 0);
        break;
    case TYPE_INT:
        snprintf(val_str, sizeof(val_str), "%d", val.i_val);
        break;
    case TYPE_FLOAT:
        snprintf(val_str, sizeof(val_str), "%.2f", val.f_val);
        break;
    default:
        fprintf(stderr, "未知类型: %d\n", type);
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return -1;
    }

    // 绑定参数
    sqlite3_bind_int(stmt, 1, key);
    sqlite3_bind_text(stmt, 2, val_str, -1, SQLITE_STATIC);
    sqlite3_bind_int(stmt, 3, type);
    sqlite3_bind_int64(stmt, 4, (sqlite3_int64)ts);

    // 执行语句
    rc = sqlite3_step(stmt);
    if (rc != SQLITE_DONE)
    {
        fprintf(stderr, "SQL 执行失败: %s\n", sqlite3_errmsg(db));
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return -1;
    }

    // 资源释放
    sqlite3_finalize(stmt);

    return 0;
}

cJSON *search_data_to_json(int key, time_t time_start, time_t time_end)
{

    sqlite3_stmt *stmt;
    const char *sql = "SELECT val, time FROM node WHERE key = ? AND time BETWEEN ? AND ? ORDER BY time ASC;";
    int rc;

    cJSON *result = cJSON_CreateObject();
    cJSON *data_array = cJSON_CreateArray();

    // 预编译
    rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK)
    {
        fprintf(stderr, "SQL 预编译失败: %s\n", sqlite3_errmsg(db));
        cJSON_AddStringToObject(result, "error", "SQL预编译失败");
        sqlite3_close(db);
        return result;
    }

    // 绑定参数
    sqlite3_bind_int(stmt, 1, key);
    sqlite3_bind_int64(stmt, 2, (sqlite3_int64)time_start);
    sqlite3_bind_int64(stmt, 3, (sqlite3_int64)time_end);

    // 遍历结果
    while (sqlite3_step(stmt) == SQLITE_ROW)
    {
        const char *val = (const char *)sqlite3_column_text(stmt, 0);
        sqlite3_int64 ts = sqlite3_column_int64(stmt, 1);

        cJSON *item = cJSON_CreateObject();
        cJSON_AddNumberToObject(item, "time", (double)ts);
        cJSON_AddStringToObject(item, "val", val);

        cJSON_AddItemToArray(data_array, item);
    }

    cJSON_AddNumberToObject(result, "key", key);
    cJSON_AddItemToObject(result, "data", data_array);
    sqlite3_finalize(stmt);
    return result;
}